<?php

namespace App\Http\Controllers\Home;

use App\Models\Collections;
use App\Models\Configs;
use App\Models\Footprints;
use App\Models\Goods;
use App\Models\GoodsCategorys;
use App\Models\GoodsEvaluates;
use App\Models\Orders;
use App\Models\Stores;
use App\Models\UserInfos;
use App\Models\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;


class GoodsController extends Controller
{
    /**
     * 商品分类页面
     * @param url home.goods.goodsCate
     * @param Request $request
     * @return bool
     */
    public function goodsCate(){
        return view('home.goods.cate');
    }
    /**
     * 商品分类
     * @param url home.goods.goodsCatesApi
     * @param Request $request
     * @return bool
     * @return salenum 销量
     * @return $lists['goods_hot']热门商品  $lists['goods_new']最新商品
     */
    public function goodsCatesApi(Request $request)
    {
        try{
            $lists = [];
            $lists['goods_cate'] = GoodsCategorys::getCascaderList();
            foreach ($lists['goods_cate'] as $key=>$val){
                $lists['goods_cate'][$key]['bool'] = false;
            }
            $fields = ['id','title','thumb','price','description','salenum','view','cate_id','cate_pid','type'];
            $lists['goods_hot'] = Goods::allLists(['hot'=>2], $fields, null, 6, 'salenum');
            $lists['goods_new'] = Goods::allLists([], $fields, null, 6, 'created_at');
            foreach ($lists['goods_hot'] as $key=>$val){
                $lists['goods_hot'][$key]['salenum'] = strlen($val['salenum'])>=4 ? '999+' : $val['salenum'];
                $lists['goods_hot'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
            }
            foreach ($lists['goods_new'] as $key=>$val){
                $lists['goods_new'][$key]['salenum'] = strlen($val['salenum'])>=4 ? '999+' : $val['salenum'];
                $lists['goods_new'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
            }
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 商品列表页面
     * @param url home.goods.goodsList
     * @param Request $request
     * @return bool
     */
    public function goodsList(){
        return view('home.goods.list');
    }
    /**
     * 商品列表
     * @param url home.goods.goodsListsApi
     * @param Request $request
     * @param cid 一级分类id
     * @param cid_id 二级分类id
     * @param page 页码
     * @param sid 排序id 1:销量 2:浏览量 3:好评量 4:积分商品(积分兑换专区)  不传或其他值：创建时间
     * @param orderby 'desc'倒叙 ‘asc'正序
     * @return bool
     */
    public function goodsListsApi(Request $request)
    {
        try{
            $map = [
                'cid' => (int)$request->get('cid'),//一级分类id
                'cid_id' => (int)$request->get('cid_id'),//二级分类id
            ];
            if (!empty($map['cid_id'])){
                $map['cid_id'] = explode(",", $map['cid_id']);
            }
            $page = (int)$request->get('page',1);//页码
            $sid = (int)$request->get('sid',2);//排序
            $orderby = (string)$request->get('orderby','desc');//排序方式
            $sort = 'created_at';
            if ($sid == 1){
                $sort = 'salenum';
            }elseif ($sid == 2){
                $sort = 'view';
            }elseif ($sid == 3){
                $sort = 'praise';
            }elseif ($sid == 4){
                $map['type'] = 3;
            }else{
                $sort = 'created_at';
            }
            $lists = [];
            $lists['cate_id'] = GoodsCategorys::getcates(['pid'=>0],['id','name','pid']);//一级分类
            //二级分类
            if(empty($map['cid'])){
                $lists['children'] = GoodsCategorys::where('pid','<>','0')->get(['id','name','pid'])->toArray();
            }else{
                $lists['children'] = GoodsCategorys::getcates(['pid'=>$map['cid']],['id','name','pid'])->toArray();
            }
            $fields = ['id','title','thumb','price','description','view','salenum','cate_id','cate_pid','type'];
            $lists['goods'] = Goods::allLists($map, $fields, $page, 10, $sort, $orderby);
            foreach ($lists['goods'] as $key=>$val){
                $lists['goods'][$key]['salenum'] = strlen($val['salenum'])>=4 ? '999+' : $val['salenum'];
                $lists['goods'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
            }

            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 商品详情页面
     * @param url home.goods.goodsDetails
     * @param Request $request
     * @return bool
     */
    public function goodsDetails(){
        return view('home.goods.details');
    }
    /**
     * 商品详情
     * @param url home.goods.goodsDetailsApi
     * @param Request $request
     * @param id 活动id
     * @param type 1:好评 2：中评 3：差评
     * @param page 页码（评价数据）
     * @return avg_good 好评率
     * @return good 好评数
     * @return middle 中评数
     * @return bad 差评数
     * @return is_collect 1:未收藏 2:已收藏
     * @return (array)store 主办方信息
     * @return store_collect 店铺1:未收藏 2:已收藏
     * @return (array)evaluates 评价数据
     * @return average_star 当前评价的平均星星
     * @return type 类型：1好评，2中评，3差评
     * @return content 内容
     * @return user_avatar 用户头像
     */
    public function goodsDetailsApi(Request $request){
        try{
            $id = (int)$request->get('id');//商品id
            if (empty($id)) return $this->writeJson(1,null,'参数错误');
            $fields = ['id','store_id','title','thumb','images','price','content','star','cate_id','cate_pid','type'];
            $lists = Goods::details(['id'=>$id], $fields);

            //判断是否收藏
            $lists['is_collect'] = 1;//默认未收藏
            $userinfo = auth()->guard('web')->user();//获取当前登录用户
            if (!empty($userinfo)){
                if ($userinfo['type'] == 1){
                    $collect = Collections::where(['collect_id'=>$id,'user_id'=>$userinfo['id'],'type'=>3])->value('collect_id');
                    $lists['is_collect'] = empty($collect) ? 1 : 2;
                }
                //添加足迹
                $foot_arr = [
                    'user_id' => $userinfo['id'],
                    'foot_id' => $id,
                    'type'    => 3,
                ];
                Footprints::create($foot_arr);
            }
            //店铺信息
            if($lists['type'] == 3){
                $base = Configs::getConfig('base');
                $lists['store'] = ['logo'=>$base['site_logo'], 'name'=>$lists['store_name']];
            }else{
                $field = ['id','user_id','store_name','logo','call','credit','hot','quality'];
                $store = Stores::details(['id'=>$lists['store_id']], $field);
                $store['master_name'] = UserInfos::where('user_id',$store['user_id'])->value('master_name');
                $store['master_phone'] = UserInfos::where('user_id',$store['user_id'])->value('master_phone');
                $store['call'] = strlen($store['call'])>=4 ? '999+' : $store['call'];
                $store['bool'] = false;
                //判断是否收藏
                $store['store_collect'] = 1;//默认未收藏
                if (!empty($userinfo) && $userinfo['type'] == 1){
                    $collect = Collections::where(['collect_id'=>$id,'user_id'=>$userinfo['id'],'type'=>4])->value('collect_id');
                    $store['store_collect'] = empty($collect) ? 1 : 2;
                }
                $lists['store'] = $store;
            }
            //评价内容
            $page = (int)$request->get('page',1);//页码
            if (empty($page)) return $this->writeJson(1,null,'页码不能为空');
            $map = [
                'goods_id' => $lists['id'],
                'type' => (int)$request->get('type',1),
            ];
            $evaluates = GoodsEvaluates::allLists($map, ['*'], $page, 3);
            foreach ($evaluates as $k=>$v){
                $evaluates[$k]['user_name'] = '**'.mb_substr($v['user_name'],-2,4,"utf-8");
            }
            $sum = GoodsEvaluates::counts(['goods_id'=>$lists['id']]);//评价总数
            $good = GoodsEvaluates::counts(['goods_id'=>$lists['id'],'type'=>1]);//好评数
            $lists['avg_good'] = empty($sum) ? 0 : intval(round (($good/$sum)*100));//好评率
//            $lists['good'] = $good;
            $lists['middle'] = GoodsEvaluates::counts(['goods_id'=>$lists['id'],'type'=>2]);//中评数
            $lists['bad'] = GoodsEvaluates::counts(['goods_id'=>$lists['id'],'type'=>3]);//差评数

            $lists['good'] = strlen($good)>=4 ? '999+' : $good;//好评数
            $lists['middle'] = strlen($lists['middle'])>=4 ? '999+' : $lists['middle'];
            $lists['bad'] = strlen($lists['bad'])>=4 ? '999+' : $lists['bad'];
            $lists['evaluates'] = $evaluates;

            Goods::where('id',$id)->increment('view');//浏览量加1
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 商品详情右侧同类型热门商品
     * @param url home.goods.detailsRightHotGoodsApi
     * @param cid 商品一级分类id
     * @param type 商品类型
     */
    public function detailsRightHotGoodsApi(Request $request)
    {
        try{
            $params = [];
            $type = (int)$request->get('type');//商品类型
            if($type == 3){
                $params['type'] = 3;
            }else{
                $params['cid'] = (int)$request->get('cid');//商品一级分类id
            }
            $fields = ['id','thumb','title','cate_pid','cate_id','price','salenum','view','type'];
            $lists = Goods::allLists($params,$fields, null,4,'salenum');
            foreach ($lists as $key=>$val){
                $lists[$key]['salenum'] = strlen($val['salenum'])>=4 ? '999+' : $val['salenum'];
                $lists[$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
            }
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 判断用户是否登录、商品库存、积分商品：积分是否足够
     * @param url home.goods.goodsJudgeApi
     * @param goods_id 商品id
     * @param goods_num 购买数量
     * @return bool
     */
    public function goodsJudgeApi(Request $request)
    {
        try{
            $user_id = auth()->guard('web')->id();
            if (empty($user_id)) return $this->writeJson(1,null,'请先登录');
            $userinfo = Users::where(['id'=>$user_id, 'status'=>1])->first(['integral','type']);
            if (empty($userinfo)) return $this->writeJson(1,null,'用户不存在');
            if ($userinfo['type'] != 1) return $this->writeJson(1,null,'只有HR才可以购买商品');

            $goods_id = (int)$request->get('goods_id');
            $goods_num = (int)$request->get('goods_num');
            $goods_info = Goods::details(['id'=>$goods_id]);
            //判断库存是否足够
            if(intval($goods_info['storage']) < intval($goods_num)){
                return $this->writeJson(1,null,'库存不足');
            }
            //判断积分是否足够
            if($goods_info['type'] == 3){
                $point_total = $goods_num * $goods_info['price'];//兑换所需总积分
                if($userinfo['integral'] < $point_total){
                    return $this->writeJson(1,null,'积分不足');
                }
            }
            return $this->writeJson(0,null, '放心购买');
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 商品收藏
     * @param url home.goods.goodsCollectApi
     * @param Request $request
     * @param collect_id 收藏内容id
     * @return bool
     */
    public function goodsCollectApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();
            if (empty($user_id)) return $this->writeJson(1,null,'请先登录');
            $collect_id = (int)$request->post('collect_id');
            if (empty($collect_id)) return $this->writeJson(1,null,'参数错误');
            $userinfo = Users::where(['id'=>$user_id, 'status'=>1])->value('type');
            if (empty($userinfo)) return $this->writeJson(1,null,'用户不存在');
            if ($userinfo != 1) return $this->writeJson(1,null,'供应商不能收藏商品');
            $collect = Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>3])->value('id');
            if (empty($collect)){
                $params = [
                    'collect_id' => $collect_id,
                    'user_id' => $user_id,
                    'collect_at' => date('Y-m-d H:i:s'),
                    'type' => 3,
                ];
                Collections::create($params);
                Goods::where('id',$collect_id)->increment('collect');
                return $this->writeJson(0, null, '收藏成功');
            }else {
                Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>3])->delete();
                return $this->writeJson(0, null, '取消收藏成功');
            }
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 评价商品
     * @param url home.goods.goodsEvaluatesApi
     * @param goods_id 商品id
     * @param goods_name 商品名称
     * @param content 内容
     * @param images 图片（最多5张）
     * @param average_star 星级
     * @param Request $request
     * @return bool
     */
    public function goodsEvaluatesApi(Request $request){
        try{
            $user_id = auth()->guard('web')->id();
            if (empty($user_id)) return $this->writeJson(1,null,'请先登录');
            $userinfo = Users::where(['id'=>$user_id, 'status'=>1])->first(['username','avatar','type']);
            if (empty($userinfo)) return $this->writeJson(1,null,'用户不存在');
            if($userinfo['type'] != 1)  return $this->writeJson(1,null,'HR才可以评价商品');

            $params = [
                'user_id' => $user_id,
                'user_name' => $userinfo['username'],
                'user_avatar' => $userinfo['avatar'],
                'goods_id' => (int)$request->post('goods_id'),
                'goods_name' => (string)$request->post('goods_name'),
                'content' => (string)$request->post('content'),
                'average_star' => (int)$request->post('average_star'),
            ];
            if($params['average_star'] == 1 || $params['average_star'] == 2){
                $params['type'] = 3;//差评
            }elseif ($params['average_star'] == 3 || $params['average_star'] == 4){
                $params['type'] = 2;//中评
            }elseif ($params['average_star'] == 5){
                $params['type'] = 1;//好评
            }

            GoodsEvaluates::create($params);
            Goods::where('id',$params['goods_id'])->increment('praise');//评论量加1
            //计算好评率
            $all = GoodsEvaluates::where(['goods_id'=>$params['goods_id']])->where('status','<>',-1)->count();
            $goods = GoodsEvaluates::where(['goods_id'=>$params['goods_id'], 'type'=>1])->where('status','<>',-1)->count();
            $credit = $goods/$all*100;
            //被评价商品星级
            if($credit <= 20){
                $star = 1;
            }elseif ($credit >20 && $credit <= 40){
                $star = 2;
            }elseif ($credit >40 && $credit <= 60){
                $star = 3;
            }elseif ($credit >60 && $credit <= 80){
                $star = 4;
            }elseif ($credit >80 && $credit <= 100){
                $star = 5;
            }
            Goods::where('id',$params['goods_id'])->update(['credit'=>$credit, 'star'=>$star]);
            return $this->writeJson(0, null, '评价成功');
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }


}